package com.zimmur.service.impl.order;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.zimmur.common.AppModuleEnum;
import com.zimmur.common.IDWorkFactory;
import com.zimmur.dao.order.ICartDao;
import com.zimmur.dao.order.ICartDesigerDao;
import com.zimmur.model.account.GoodsUser;
import com.zimmur.model.fdfs.StorageFiles;
import com.zimmur.model.goods.Goods;
import com.zimmur.model.goods.GoodsSize;
import com.zimmur.model.order.Cart;
import com.zimmur.model.order.CartDesiger;
import com.zimmur.model.order.view.CartView;
import com.zimmur.model.order.view.ReceiveOrderModel;
import com.zimmur.service.IUserService;
import com.zimmur.service.fdfs.IStorageFilesService;
import com.zimmur.service.goods.IGoodsService;
import com.zimmur.service.goods.IGoodsSizeService;
import com.zimmur.service.order.ICartService;
import com.zimmur.tools.DateUtils;

@Service("cartServiceImpl")
public class CartServiceImpl implements ICartService{
	private static Logger log = LoggerFactory.getLogger(CartServiceImpl.class);
	
	@Resource
	private ICartDao cartDao;
	@Resource
	private ICartDesigerDao cartDesigerDao;
	
	@Resource
	private IGoodsService goodsService;
	@Resource
	private IGoodsSizeService goodsSizeService;
	@Resource
	private IStorageFilesService storageFilesService;
	@Resource
	private IUserService userService;
	
	@Transactional(isolation=Isolation.READ_COMMITTED,timeout=100,rollbackFor={RuntimeException.class,Exception.class})
	public boolean addCart(long userId, long goodsId, long sizeCode, int quantity,int isPrepay) {
		boolean bRet = false;
		try{
			Goods goods = goodsService.selectByGoodsId(goodsId);
		    GoodsSize goodsSize = goodsSizeService.selectbySizeId(sizeCode);
		    if(goods!=null && goodsSize != null){
	    	//衣匠商品，才能加购物车
    		Cart cart = new Cart();
    		cart.setGoodsId(goodsId+"");		
    		cart.setColorCode(goodsSize.getColorCode());
    		cart.setSize(goodsSize.getSize());		
    		cart.setUserId(userId);
    		cart.setSizeCode(sizeCode+"");
    		cart.setIsPrepay(isPrepay);
    		CartDesiger desiger = new CartDesiger();
    		
    		long desigerUserId = goods.getUserId();			
    		desiger.setDesigerId(desigerUserId);
    		desiger.setUserId(userId);
    		desiger.setUpdateDate(DateUtils.getNowUnixTime());
    		CartDesiger checkDesiger = cartDesigerDao.selectByPrimaryKey(desiger);
    		if(checkDesiger == null){
    			GoodsUser desigerUser = userService.selectByUserId(desigerUserId);
    			if(desigerUser!=null){
    				desiger.setDesigerName(desigerUser.getNickName());
    				desiger.setOccupation(desigerUser.getOccupation());
    				cartDesigerDao.insertSelective(desiger);
    			}
    		}else{
    			cartDesigerDao.updateByPrimaryKeySelective(desiger);
    		}
    		
    		Cart checkCart = cartDao.selectByUserIdAndColorAndSize(cart);
    		if(checkCart == null){
    			cart.setCartId(IDWorkFactory.getID(AppModuleEnum.Cart)+"");
    			cart.setColor(goodsSize.getColor());
    			cart.setCoverImage(goods.getCoverImage());
    			cart.setDesigerId(goods.getUserId());
    			cart.setQuantity(quantity);
    			cart.setTitle(goods.getTitle());
    			cart.setCreateDate(DateUtils.getNowUnixTime());
    			cartDao.insertSelective(cart);
    		}else{
    			if(!checkCart.getIsPrepay().equals(isPrepay)){
    				checkCart.setIsPrepay(isPrepay);
    			}
    			int curQuantity = checkCart.getQuantity();
    			checkCart.setQuantity(curQuantity+quantity);
    			cartDao.updateQuantity(checkCart);
    		}
    		bRet = true;
	    }
		}catch(Exception er){
			log.error(er.getMessage());
			throw new RuntimeException(er.getMessage());
		}
		return bRet;
	}

	@Override
	public boolean updateCart(long cartId, int quantity) {
		if(cartId>0 && quantity>0){
			Cart cart = new Cart();
			cart.setCartId(cartId+"");
			cart.setQuantity(quantity);
			
			return cartDao.updateQuantity(cart)>0?true:false;
		}
		return false;
	}

	@Override
	public boolean delCart(long cartId) {
		Cart cart = cartDao.selectByPrimaryKey(cartId);
		if(cart == null)
			return false;
		
		boolean bRet = cartDao.deleteByPrimaryKey(cartId)>0?true:false;
		int iCount = cartDao.selectByDesigerId(cart.getDesigerId());
		if(iCount == 0){
			CartDesiger desiger = new CartDesiger();
			desiger.setUserId(cart.getUserId());
			desiger.setDesigerId(cart.getDesigerId());
			cartDesigerDao.deleteByPrimaryKey(desiger);
		}
		return bRet;
	}

	@Override
	public List<Cart> getCartList(long userId) {
		List<Cart> cartList = cartDao.selectCartByUserId(userId);
		if(cartList!=null&&!cartList.isEmpty()){
			for(Cart c:cartList){
				//1.查询封面图的URL
				StorageFiles storageFiles =storageFilesService.selectByFileId(Long.parseLong(c.getCoverImage()));
				if(storageFiles!=null){
					c.setCoverImageUrl("/"+storageFiles.getStoragegroup()+"/"+storageFiles.getStorageid());
				}
				//2.查询商品的折扣率
				Goods goods = goodsService.selectByGoodsId(Long.parseLong(c.getGoodsId()));
				if(goods!=null){
					c.setOffPercent(goods.getOffPercent());
				}
			}
		}
		return cartList;
	}

	@Override
	public int countUserCart(long userId) {
		return cartDao.selectCountByUserId(userId);
	}
	
	public String countUserCartAmount(long userId){
		double amount = 0.0;
		
		List<Cart> carts = getCartList(userId);
		if(carts.size()>0){
			Iterator<Cart> iterator = carts.iterator();
			while(iterator.hasNext()){
				Cart item = iterator.next();
				BigDecimal multiply = item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
				amount += multiply.doubleValue();
			}
		}
		
		return new DecimalFormat("#.##").format(amount);
	}

	@Override
	public boolean delCart(long userId, List<ReceiveOrderModel> models) {
		boolean bRet = false;
		try{
			Cart cart = new Cart();
			cart.setUserId(userId);
			
			Cart checkCart = null;
			for (ReceiveOrderModel model : models) {
				cart.setGoodsId(model.getGoodsId());
				cart.setSizeCode(model.getSizeCode()+"");
				checkCart = cartDao.selectByUserIdAndColorAndSize(cart);
				if(checkCart != null){
					cartDao.deleteByPrimaryKey(Long.parseLong(checkCart.getCartId()));
				}
				checkCart = null;
			}
			bRet = true;
		}catch(Exception er){
			log.error(er.getMessage());
			bRet=false;
		}
		
		return bRet;
	}

	@Override
	public int delCart(long cartId, long goodsId) {
		int bRet = 0;
		try {
			Cart cart = new Cart();
			cart.setCartId(cartId+"");
			cart.setGoodsId(goodsId+"");
			bRet = cartDao.deleteByGoodsId(cart);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return bRet;
	}
	
}
